# -*- encoding:utf8 -*-
import smtplib
from email.mime.text import MIMEText
import ConfigParser
import time,sys
import urllib2
import os
import traceback

#监控进程状态
def isAlive(check_cmd):
    output = os.popen(check_cmd)
    status = output.read()
    if len(status) ==0:
        return False
    else:
        return True

#发送邮件
class Mailman(object):
    def __init__(self,msg_from,msg_to,passwd,server,server_port,subject = "服务器监控"):
        self.msg_from = msg_from
        self.msg_to = msg_to
        self.passwd = passwd
        self.subject = subject
        self.server = server
        self.server_port = server_port

    def mail(self,message):
        # 主题
        #content = "这是我使用python smtplib及email模块发送的邮件"# 正文
        msg = MIMEText(message)
        msg['Subject'] = self.subject
        msg['From'] = self.msg_from
        msg['To'] = self.msg_to
        s = None
        try:
            s = smtplib.SMTP_SSL(self.server, self.server_port) # 邮件服务器及端口号
            s.login(self.msg_from, self.passwd)
            s.sendmail(self.msg_from, self.msg_to, msg.as_string())
            print("发送成功")
        except:
            print("发送失败")
        finally:
            s.quit()

def getCurTime():
    return time.strftime("%Y%m%d %H:%M:%S",time.localtime(time.time()))

#监控服务项配置
def getConfig(config_file):
    config = ConfigParser.ConfigParser()
    config.read(config_file)
    dict_config ={}
    for section in config.sections():
        service_info = {}
        dict_config[section] = service_info
        #监控的服务名称
        service_info['check_cmd'] = config.get(section,'check_cmd')
        service_info['start_cmd'] = config.get(section, 'start_cmd')
        #短信通知配置
        service_info['to_phone_number'] = config.get(section, 'to_phone_number')
        #邮件通知配置
        service_info['check_interval'] = config.getint(section,'check_interval')
        service_info['mail_from'] = config.get(section,'mail_from')
        service_info['mail_pwd'] = config.get(section,'mail_pwd')
        service_info['mail_server'] = config.get(section,'mail_server')
        service_info['mail_server_port'] = config.getint(section,'mail_server_port')
        service_info['mail_to'] = config.get(section,'mail_to')
        service_info['subject'] = config.get(section,'subject')

        service_info['errror_message'] = config.get(section,'errror_message')
    return dict_config

#重启服务
def restartService(strs_start_cmd):
    list_cmd = strs_start_cmd.split("|")
    for cmd in list_cmd:
        output = os.popen(cmd)
        #print output.read()

#根据配置文件，对服务列表监控
def watchService(config_file):
    dict_config = getConfig(config_file)
    for process_name,process_config in dict_config.items():
        check_cmd = process_config['check_cmd']
        #check_interval = item['check_interval']
        status = isAlive(check_cmd)
        if status == False: #服务不存在
            start_cmd = process_config['start_cmd']
            restartService(start_cmd)
            print("%s %s:not running,restart" % (process_name, getCurTime()))
            str_phone_number = process_config['to_phone_number']
            errror_message = process_config['errror_message']
            errror_message = '%s %s:%s'%(getCurTime(),process_name,errror_message)
            errror_message = urllib2.quote(errror_message)
            list_phone_number = str_phone_number.split('|')
            for phone_number in list_phone_number:
                url = 'http://10.116.32.183:10080/mws/api_sendMessage.action?message=%s&tel=%s'%(errror_message,phone_number)
                print(url)
                file = urllib2.urlopen(url)
                content = file.read()  # 读取全部
                print(content.decode('utf8'))

            msg_from = process_config['mail_from']  # 发送方邮箱
            mail_server = process_config['mail_server']
            mail_server_port = process_config['mail_server_port']
            passwd = process_config['mail_pwd']  # 填入发送方邮箱的授权码
            msg_to = process_config['mail_to']  # 收件人邮箱
            subject = process_config['subject']
            message = process_config['errror_message']
            mm = Mailman(msg_from,msg_to,passwd,mail_server,mail_server_port,subject)
            mm.mail('%s:%s'%(process_name,message))
        else:
            print("%s %s:OK"%(process_name,getCurTime()))

#循环
def loop(config_file,check_interval):
    while True:
        try:
            watchService(config_file)
            time.sleep(check_interval)
            print('awake')
        except Exception as e:
            print(traceback.print_exc())

if __name__ == '__main__':
    config_file = None
    if len(sys.argv) <2:
        print 'which config to use?'
        sys.exit(0)

    check_interval = 60
    if len(sys.argv) >= 3:
        temp = int(sys.argv[2])
        if temp > check_interval:
            check_interval = temp
    config_file = sys.argv[1]
    loop(config_file,check_interval)
    '''
    restartService('nohup python2 test.py &')
    print isAlive('ps -aux|grep test.py|grep -v grep')
    '''